package com.hupu.jrs

import android.app.Application
import com.facebook.cache.disk.DiskCacheConfig
import com.facebook.common.util.ByteConstants
import com.facebook.drawee.backends.pipeline.Fresco
import com.facebook.imagepipeline.backends.okhttp3.OkHttpImagePipelineConfigFactory
import com.facebook.imagepipeline.cache.MemoryCacheParams
import com.facebook.imagepipeline.decoder.SimpleProgressiveJpegConfig
import com.hupu.jrs.components.storage.UserStorage
import com.hupu.jrs.injector.component.ApplicationComponent
import com.hupu.jrs.util.ToastUtil
import com.liulishuo.filedownloader.FileDownloader
import com.squareup.leakcanary.LeakCanary
import okhttp3.OkHttpClient
import javax.inject.Inject

/**
 * Created by sll on 2016/3/8.
 */
class MyApplication : Application() {
    @Inject
    internal var mUserStorage: UserStorage? = null
//    @Inject
//    internal var mUserDao: UserDao? = null
    @Inject
    internal var mOkHttpClient: OkHttpClient? = null
    var applicationComponent: ApplicationComponent? = null
        private set

    override fun onCreate() {
        super.onCreate()
        initComponent()
        initUser()
        FileDownloader.init(this) { mOkHttpClient }
        initFrescoConfig()
        ToastUtil.register(this)
        LeakCanary.install(this)
    }

    private fun initComponent() {
//        applicationComponent = DaggerApplicationComponent.builder().applicationModule(ApplicationModule(this)).build()
//        applicationComponent!!.inject(this)
    }

    private fun initUser() {
//        val users = mUserDao!!.queryBuilder()
//                .where(UserDao.Properties.Uid.eq(SettingPrefUtil.getLoginUid(this)))
//                .list()
//        if (!users.isEmpty()) {
//            mUserStorage!!.login(users.get(0))
//        }
    }

    private fun initFrescoConfig() {
        val bitmapCacheParams = MemoryCacheParams(MAX_MEMORY_CACHE_SIZE, // Max total size of elements in the cache
                Integer.MAX_VALUE, // Max entries in the cache
                MAX_MEMORY_CACHE_SIZE, // Max total size of elements in eviction queue
                Integer.MAX_VALUE, // Max length of eviction queue
                Integer.MAX_VALUE)
        val config = OkHttpImagePipelineConfigFactory.newBuilder(this, mOkHttpClient!!)
                .setProgressiveJpegConfig(SimpleProgressiveJpegConfig())
                .setBitmapMemoryCacheParamsSupplier { bitmapCacheParams }
                .setMainDiskCacheConfig(
                        DiskCacheConfig.newBuilder(this).setMaxCacheSize(MAX_DISK_CACHE_SIZE.toLong()).build())
                .setDownsampleEnabled(true)
                .build()
        Fresco.initialize(this, config)
    }

    companion object {

        val MAX_DISK_CACHE_SIZE = 50 * ByteConstants.MB
        private val MAX_HEAP_SIZE = Runtime.getRuntime().maxMemory().toInt()
        val MAX_MEMORY_CACHE_SIZE = MAX_HEAP_SIZE / 8
    }
}
